package com.example.common.util;

import lombok.Builder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * <h1>吐流方式下载文件</h1>
 * Created by hanqf on 2021/7/30 21:46.
 */

@Builder
public class CP_DownloadFileUtil {
    private String fileName;
    private InputStream inputStream;
    private Integer fileSize;

    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachement;filename="
                + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        response.setContentLength(fileSize.intValue());

        try(InputStream in = inputStream;
            OutputStream out = response.getOutputStream()) {

            byte[] buff = new byte[1024];
            int readCount = 0;
            while ((readCount = in.read(buff)) != -1) {
                out.write(buff, 0, readCount);
            }

        }

        response.setStatus(HttpServletResponse.SC_OK);
        response.flushBuffer();
    }
}
